const { Service } = require('egg')
const { tableToList, transformArray, getTerm } = require('../utils/tools')

module.exports = class PlanService extends Service {
  /**
   * 培养计划
   * @return {Array} *
   */
  async table() {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/pyfa/pyfa_query`
    const promiseList = [this.ctx.curl(apiUrl, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    }), this.ctx.curl(`${this.ctx.state.baseUrl}/jsxsd/pyfa/topyfamx`, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })]
    const [res, res_] = await Promise.all(promiseList)

    /* 序号 开课学期 课程编号 课程名称 开课单位 学分 总学时 考核方式 课程性质 课程属性 是否考试 */
    const header = ['课程名称', '属性', '性质', '学分', '考核方式', '学时', '开课单位'] // 列名称
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#dataList')
        const columnNeed = [3, 9, 8, 5, 7, 6, 4] // 需要提取的列序号
        const info = {}
        for (let i = 1; i < tableList.length; i++) {
          const term = tableList[i][1]
          if ((term in info) === false) { info[term] = [] }
          const tem = []
          columnNeed.forEach((idx) => { tem.push(tableList[i][idx] || '') })
          info[term].push(tem)
        }

        /* 执行计划中的数据不完全，在培养计划及完成情况中补充 */
        const tableList_ = tableToList(res_.data.toString(), '#mxh')
        const year = this.ctx.data.sid.slice(0, 4) // 对学号进行处理，得到入学年份
        const dict = transformArray(
          tableList_,
          13,
          (key) => (getTerm(year, key)),
          (value) => ([3, 6, 5, 7, -1, 12, -1].map((idx) => (value[idx] || ''))),
        )
        for (const term in dict) {
          if (Object.keys(info).includes(term)) continue
          else if (!term.includes('NaN')) info[term] = dict[term]
        }

        return { table: info, header }
      } catch (err) {
        console.log('err', err)
        return err
      }
    }
    return { table: {}, header }
  }
}
